using System;
using System.Linq;
using DNT.RavenQA.Core.Models;
using DNT.RavenQA.Web.Infrastructure.Extensions;
using Raven.Client;
using Raven.Client.Linq;

namespace DNT.RavenQA.Web.Infrastructure.QueryModel
{
    public class LatestUserQuestionsQuery : IQuery<Question>
    {
        public LatestUserQuestionsQuery(Int32 userId)
        {
            _userId = userId;
        }

        private readonly Int32 _userId;

        public IQueryable<Question> ExecuteWithStats(IDocumentSession session,
                                                     out RavenQueryStatistics stats)
        {
            var id = session.GetRealId<User>(_userId);

            return session.Query<Question>()
                          .Include(x => x.User.Id)
                          .Statistics(out stats)
                          .Where(q => q.User.Id == id)
                          .OrderByDescending(i => i.LastUpdateOn);
        }

        public IQueryable<Question> Execute(IDocumentSession session)
        {
            var id = session.GetRealId<User>(_userId);

            return session.Query<Question>()
                          .Include(x => x.User.Id)
                          .Where(q => q.User.Id == id)
                          .OrderByDescending(i => i.LastUpdateOn);
        }
    }
}